import React, { useEffect, useRef, useState, forwardRef } from 'react'
import {
    DatePicker,
    Form,
    Input,
    Select,
    Button,
    message
} from 'antd';
import { getCategoryServiceById, getSerivceInformation, getServicesByCategoryId } from '../../../utils/request/get';
import './index.css'
import { useSelector } from 'react-redux';
import { ZERODAY } from '../../../redux/constant'
import { getTime } from '../../../utils/time';
import { addBankRecord, addCustomer, addRecord } from '../../../utils/request/post';
import { findIdByName } from '../../../utils/array';
import { assignUndefinedValue } from '../../../utils/common';
import { useNavigate } from 'react-router-dom';
import moment from 'moment';
import { ConfigProvider } from 'antd'
import zhCN from 'antd/lib/locale/zh_CN'

const { Option } = Select;
const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 9 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
    },
};

const NewService = forwardRef((props, ref) => {
    const navigate = useNavigate()
    const { username, userId } = useSelector(state => state.TokenReducer.token)
    const [categories, setCategories] = useState([])
    const [services, setServices] = useState([])
    const [channels, setChannels] = useState([])
    const [locations, setLocations] = useState([])
    const [auditStates, setAuditStates] = useState([])
    const [header, setHeader] = useState([])
    const [currentCategory, setCurrentCategory] = useState('')
    const [isFirst, setIsFirst] = useState(true)
    let serviceForm = useRef(null)
    serviceForm = ref ? ref : serviceForm
    const { isUpdate, data } = props

    useEffect(() => {
        async function fetchData() {
            const { categories, services, channels, locations, auditStates, headers } = await getSerivceInformation()
            setCategories(categories)
            setServices(services)
            setChannels(channels)
            setLocations(locations)
            setAuditStates(auditStates)
            setHeader(headers[0])
        }
        fetchData()
    }, [])

    const handleFieldsValueChange = (changedValue, allValues) => {
        const { categoryName, serviceName, acceptedTime, timeLimit } = allValues
        /** isFirst 避免 categoryName serviceName 同时存在时，编辑其他值仍然请求数据*/
        if (categoryName && serviceName && isFirst) {
            const categoryId = findIdByName(categories, categoryName)
            const serviceId = findIdByName(services, serviceName)
            setCurrentCategory(categoryName)
            getCategoryServiceById(categoryId, serviceId).then(res => {
                // console.log(res.data.category_service);
                const { category_service } = res.data
                const { Bank, Circulation, Risk, Type, timeLimit } = category_service
                const circulation = Circulation.title
                const type = Type.title
                const risk = Risk.title
                const obj = {
                    ...allValues,
                    circulation,
                    risk,
                    type,
                    ...Bank,
                    bankName: Bank.name,
                    timeLimit: timeLimit === 0 ? ZERODAY : timeLimit + "个工作日",
                }
                serviceForm.current.setFieldsValue(obj)
                setIsFirst(false)
            })
        } else if (categoryName && currentCategory !== categoryName) {
            /* 只有 categoryName 发生变化才重新请求 Services */
            const categoryId = findIdByName(categories, categoryName)
            // 解除限制
            setIsFirst(true)
            setCurrentCategory(categoryName)
            getServicesByCategoryId(categoryId).then(res => {
                const { services } = res.data
                const list = services.map(x => {
                    return {
                        title: x.Service.title,
                        id: x.Service.id
                    }
                })
                setServices(list)
            })
        }
        /* 自动计算截止日期 */
        if (acceptedTime && timeLimit && !isUpdate) {
            // const endTime = calculateDate(acceptedTime, parseInt(timeLimit.split('个')[0]));
            // allValues['endTime'] = endTime
            // setFieldValue('endTime', endTime) 无法改变值
            serviceForm.current.setFieldsValue({ ...allValues })
        }
    }

    // const calculateDate = (startDate, days) => {
    //     var targetDateObj = startDate.clone().add(days, 'd');
    //     return targetDateObj;
    // }

    const isBankDisabled = (value) => {
        return value === '不用录入' ? true : false
    }

    const onFinish = async (value) => {
        // console.log(value);
        const {
            categoryName, serviceName, channel, location, eLocation, notes, auditState,
            customerName, code, unitName, identityId, phoneNumber,
            bankName, owner, number
        } = value
        const categoryId = findIdByName(categories, categoryName)
        const serviceId = findIdByName(services, serviceName)
        const auditId = findIdByName(auditStates, auditState)
        const channelId = findIdByName(channels, channel)
        const locationId = findIdByName(locations, location)

        const acceptedTime = getTime(value.acceptedTime)
        const endTime = getTime(value.endTime)
        // 处理新客户
        let customer = {
            name: customerName,
            identityId,
            code: assignUndefinedValue(code),
            unitName: assignUndefinedValue(unitName),
            phoneNumber: assignUndefinedValue(phoneNumber)
        }
        const customerRes = await addCustomer(customer)
        const newCustomer = customerRes && customerRes.data.customer
        const customerId = newCustomer.id

        let bankId = 2
        // 处理银行卡信息
        if (bankName === "不用录入") {
            bankId = 1
        } else if (bankName !== "" || owner !== "" || number !== "") {
            const bankRecord = {
                name: bankName,
                owner: assignUndefinedValue(owner),
                number: assignUndefinedValue(number),
            }
            const { data: { bank } } = await addBankRecord(bankRecord)
            if (bank.length !== 0) {
                bankId = bank.id
            }
        }
        // 处理业务记录
        let obj = {
            categoryId, serviceId, customerId, channelId, locationId, eLocation,
            userId, bankId, acceptedTime, endTime,
            notes: assignUndefinedValue(notes),
            auditId, auditUserId: 0
        }
        // console.log(obj);
        const recordRes = await addRecord(obj)
        // console.log(recordRes);
        if (recordRes.status === 200) {
            message.success("添加成功")
            navigate("/service-manage/list")
        } else {
            message.error("添加失败")
        }
    }

    const getInitialValue = () => {
        if (isUpdate) {
            return { ...data }
        } else {
            return { username, auditState: "未审核" }
        }
    }

    const disabledDate = (current) => {
        // Can not select days before today and today
        return current && current > moment(new Date())
    }

    const endDisableDate = (current) => {
        return current && current < moment(new Date(new Date().getTime() - 24 * 60 * 60 * 1000))
    }

    return (
        <Form
            ref={serviceForm}
            {...formItemLayout}
            initialValues={getInitialValue()}
            onValuesChange={handleFieldsValueChange}
            onFinish={onFinish}
            className='serviceForm'
        >
            <div className='form-item-column'>
                <Form.Item
                    label={header['categoryName']}
                    name='categoryName'
                    rules={[{
                        required: true,
                        message: '请选择主项名称'
                    }]}
                    className='layoutItem'
                >
                    <Select placeholder="主项名称" allowClear loading={categories.length === 0} showSearch>
                        {
                            categories.map(item => {
                                return (
                                    <Option value={item.title} key={item.id}>{item.title}</Option>
                                )
                            })
                        }
                    </Select>
                </Form.Item>
                <Form.Item
                    label={header['serviceName']}
                    name='serviceName'
                    rules={[{
                        required: true,
                        message: '请选择办理项名称'
                    }]}
                    className='layoutItem'
                >
                    <Select placeholder="办理项名称" loading={services.length === 0} showSearch>
                        {
                            services.map(item => {
                                return (
                                    <Option value={item.title} key={item.id}>{item.title}</Option>
                                )
                            })
                        }
                    </Select>
                </Form.Item>
                <Form.Item
                    label={header['circulation']}
                    name='circulation'
                    rules={[{
                        required: true,
                        message: '请选择流转情况'
                    }]}
                    className='layoutItem'
                >
                    <Input disabled />
                </Form.Item>
                <Form.Item
                    label={header['type']}
                    name='type'
                    rules={[{
                        required: true,
                        message: '请选择事项类型'
                    }]}
                    className='layoutItem'
                >
                    <Input disabled />
                </Form.Item>
                <Form.Item
                    label={header['risk']}
                    name='risk'
                    rules={[{
                        required: true,
                        message: '请选择风险等级'
                    }]}
                    className='layoutItem'
                >
                    <Input disabled />
                </Form.Item>
                <Form.Item
                    label={header['timeLimit']}
                    name='timeLimit'
                    rules={[{
                        required: true,
                        message: '请选择办结时限'
                    }]}
                    className='layoutItem'
                >
                    <Input disabled />
                </Form.Item>
                <Form.Item
                    label={header['unitName']}
                    name='unitName'
                    rules={[{
                        required: false,
                        message: '请输入单位名称'
                    }]}
                    className='layoutItem'
                >
                    <Input placeholder='请输入单位名称' />
                </Form.Item>
                <Form.Item
                    label={header['code']}
                    name='code'
                    rules={[{
                        required: false,
                        message: '请输入单位编号'
                    }]}
                    className='layoutItem'
                >
                    <Input placeholder='请输入单位编号' />
                </Form.Item>
                <Form.Item
                    label={header['customerName']}
                    name='customerName'
                    rules={[{
                        required: true,
                        message: '请选择姓名'
                    }]}
                    className='layoutItem'
                >
                    <Input placeholder='请输入姓名' />
                </Form.Item>
                <Form.Item
                    label={header['identityId']}
                    name='identityId'
                    rules={[{
                        required: true,
                        message: '请输入身份证号',
                        len: 18
                    }]}
                    className='layoutItem'
                >
                    <Input placeholder='请输入身份证号' />
                </Form.Item>
                <Form.Item
                    label={header['channel']}
                    name='channel'
                    rules={[{
                        required: true,
                        message: '请选择受理渠道'
                    }]}
                    className='layoutItem'
                >
                    <Select placeholder="受理渠道" allowClear loading={channels.length === 0} showSearch>
                        {
                            channels.map(item => {
                                return (
                                    <Option value={item.title} key={item.id}>{item.title}</Option>
                                )
                            })
                        }
                    </Select>
                </Form.Item>
                <Form.Item
                    label={header['username']}
                    name='username'
                    rules={[{
                        required: true,
                    }]}
                    className='layoutItem'
                >
                    <Input disabled />
                </Form.Item>

                <Form.Item
                    label={header['eLocation']}
                    name='eLocation'
                    rules={[{
                        required: true,
                        message: '请输入档案编号(位置)'
                    }]}
                    className='layoutItem'
                >
                    <Input placeholder='请输入档案编号(位置)' />
                </Form.Item>
                <Form.Item
                    label={header['location']}
                    name='location'
                    rules={[{
                        required: true,
                        message: '请选择档案存储位置'
                    }]}
                    className='layoutItem'
                >
                    <Select placeholder="档案存储位置" allowClear loading={locations.length === 0} showSearch>
                        {
                            locations.map(item => {
                                return (
                                    <Option value={item.title} key={item.id}>{item.title}</Option>
                                )
                            })
                        }
                    </Select>
                </Form.Item>
                <Form.Item
                    label={header['acceptedTime']}
                    name='acceptedTime'
                    rules={[{
                        required: true,
                        message: '请选择受理时间'
                    }]}
                    className='layoutItem'
                >
                    <ConfigProvider locale={zhCN}>
                        <DatePicker placeholder='请选择受理时间' disabledDate={disabledDate} />
                    </ConfigProvider>

                </Form.Item>
                <Form.Item
                    label={header['endTime']}
                    name='endTime'
                    rules={[{
                        required: true,
                        message: '请选择规定办结时间'
                    }]}
                    className='layoutItem'
                >
                    <DatePicker placeholder='请选择规定办结时间' disabledDate={endDisableDate} disabled={serviceForm.current?.getFieldValue("endTime")} />
                </Form.Item>
                <Form.Item
                    label={header['phoneNumber']}
                    name='phoneNumber'
                    rules={[{
                        required: false,
                        message: '请输入联系电话'
                    }]}
                    className='layoutItem'
                >
                    <Input placeholder='请输入联系电话' />
                </Form.Item>
                <Form.Item
                    label={header['bankName']}
                    name='bankName'
                    rules={[{
                        required: true,
                        message: '请输入银行类别/开户行'
                    }]}
                    className='layoutItem'
                >
                    <Input placeholder='请输入银行类别/开户行' disabled={isBankDisabled(serviceForm.current?.getFieldValue("bankName"))} />
                </Form.Item>
                <Form.Item
                    label={header['owner']}
                    name='owner'
                    rules={[{
                        required: true,
                        message: '请输入银行卡户名/单位账户'
                    }]}
                    className='layoutItem'
                >
                    <Input placeholder='请输入银行卡户名/单位账户' disabled={isBankDisabled(serviceForm.current?.getFieldValue("owner"))} />
                </Form.Item>
                <Form.Item
                    label={header['number']}
                    name='number'
                    rules={[{
                        required: true,
                        message: '请输入银行账号/单位账号'
                    }]}
                    className='layoutItem'
                >
                    <Input placeholder='请输入银行账号/单位账号' disabled={isBankDisabled(serviceForm.current?.getFieldValue("number"))} />
                </Form.Item>
                <Form.Item
                    label={header['notes']}
                    name='notes'
                    rules={[{
                        required: false,
                        message: '请输入备注'
                    }]}
                    className='layoutItem'
                >
                    <Input placeholder='请输入备注' />
                </Form.Item>
                <Form.Item
                    label={header['auditState']}
                    name='auditState'
                    rules={[{
                        required: false,
                        message: '请选择审核状态'
                    }]}
                    className='layoutItem'
                >
                    <Select placeholder="审核状态" allowClear loading={auditStates.length === 0} showSearch>
                        {
                            auditStates.map(item => {
                                return (
                                    <Option value={item.title} key={item.id}>{item.title}</Option>
                                )
                            })
                        }
                    </Select>
                </Form.Item>
                <Form.Item
                    label={header['auditSuggest']}
                    name='auditSuggest'
                    rules={[{
                        required: true,
                        message: '请输入审核建议'
                    }]}
                    className='layoutItem'
                >
                    <Input placeholder='请输入审核建议' />
                </Form.Item>
            </div>
            {isUpdate ? "" : <Button type="primary" htmlType="submit" className="login-form-button">
                提交
            </Button>}
        </Form>
    )
})

export default NewService